/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rockville.httpRequest;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;
/**
 *
 * @author Rock
 */
public class HttpRequestUrl {
    private static final Logger log=Logger.getLogger(HttpRequestUrl.class);
    
	public static String getURLResponse(String urlStr) {
	    StringBuffer URLresult = new StringBuffer("");
	    try {
	        URL url = new URL(urlStr);
	        URLConnection connection = url.openConnection();
	        //connection.setDoOutput(true);
	        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        String inputLine;
	        while ((inputLine = in.readLine()) != null) {
	            URLresult.append(inputLine);
	        }
	        in.close();
	    } catch (Exception exc) {
	        log.error("getURLResponse, url:"+urlStr, exc);
	        return "";
	    }
	    return URLresult.toString().trim();
	}
    
    public static String HttpGetUrl(String strUrl) {
        String strResponse = "";
        //log.debug("strUrl: " + strUrl);
        try {
            java.net.URL url = new java.net.URL(strUrl);
            java.net.HttpURLConnection connection = null;
            java.net.HttpURLConnection.setFollowRedirects(true);
            connection = (java.net.HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            
            connection.setAllowUserInteraction(true);
            connection.setDefaultUseCaches(false);
            connection.setRequestProperty("contenttype", "text/html");

            /*
            connection.setRequestProperty("Content-length", "0");
            PrintWriter pw = new PrintWriter(connection.getOutputStream());            
            pw.flush();
            pw.close();
            */
            int intResponseCode = connection.getResponseCode();
            //log.debug("" + intResponseCode + " : " + strUrl + " in HttpRequestUrl(String strUrl,String strParamName,String strParamValue) in MZReports.java");
            if (intResponseCode != 200) {
                //log.debug("response code from " + strUrl + " is not 200");
                strResponse = "-1";
                return strResponse;
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                strResponse += inputLine;
            //log.debug(strResponse);
            }
            in.close();

            connection.disconnect();
            connection = null;


        } catch (Exception e) {
            log.error("Exception in url(" + strUrl, e);
            strResponse = "-1";
        }
        return strResponse;
    }
    public static String HttpGetUrl_BasicAuthentication(String strUrl, String strUserName, String strPassword) {
        String strResponse = "";
        java.net.URL url = null;
        java.net.HttpURLConnection connection = null;
        //log.debug("strUrl: " + strUrl);
        try {
            url = new java.net.URL(strUrl);
            java.net.HttpURLConnection.setFollowRedirects(true);
            connection = (java.net.HttpURLConnection) url.openConnection();            
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
            connection.setRequestProperty("Content-Length", "0");
            connection.setRequestProperty("Connection", "close");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            
            connection.setAllowUserInteraction(true);
            connection.setDefaultUseCaches(false);
            
            //Base64 b64 = new Base64();
            String userPass;
            userPass = strUserName + ":" + strPassword;
            userPass=com.rockville.httpRequest.Base64Coder.encodeString(userPass);
            connection.setRequestProperty("Authorization", "Basic " + userPass);
            

            /*
            connection.setRequestProperty("Content-length", "0");
            PrintWriter pw = new PrintWriter(connection.getOutputStream());            
            pw.flush();
            pw.close();
            */
            int intResponseCode = connection.getResponseCode();
            //log.debug("" + intResponseCode + " : " + strUrl + " in HttpRequestUrl(" + strUrl + ","+strUserName+","+strPassword+") in "+this.getClass().getName());
            if (intResponseCode != 200) {
                log.debug("response code from " + strUrl + " is not 200");
                strResponse = "-1";
                return strResponse;
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                strResponse += inputLine;
            //log.debug(strResponse);
            }
            in.close();
            
        } catch (Exception e) {
            log.error("Exception (" + strUrl + ") ", e);
            strResponse = "-1";
        }
        finally {
            try {
                connection.disconnect();
                connection = null;
            }
            catch(Exception ex) {
                connection = null;
            }
        }
        return strResponse;
    }
    public static BufferedReader HttpGetUrl_BasicAuthentication_BR(String strUrl, String strUserName, String strPassword) {
        BufferedReader in = null;
        java.net.URL url = null;
        java.net.HttpURLConnection connection = null;
        
        try {
            url = new java.net.URL(strUrl);
            java.net.HttpURLConnection.setFollowRedirects(true);
            connection = (java.net.HttpURLConnection) url.openConnection();            
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
            connection.setRequestProperty("Content-Length", "0");
            connection.setRequestProperty("Connection", "close");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            
            connection.setAllowUserInteraction(true);
            connection.setDefaultUseCaches(false);
            
            //Base64 b64 = new Base64();
            String userPass;
            userPass = strUserName + ":" + strPassword;
            userPass=com.rockville.httpRequest.Base64Coder.encodeString(userPass);
            connection.setRequestProperty("Authorization", "Basic " + userPass);
            
            int intResponseCode = connection.getResponseCode();
            if (intResponseCode != 200) {
                log.debug("response code from " + strUrl + " is not 200");
                return null;
            }

            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            
            return in;
            
        } catch (Exception e) {
            log.debug("Exception Url(" + strUrl + ") ", e);
        }
        return null;
    }
    public static BufferedInputStream HttpGetUrl_BasicAuthentication_BInputStream(String strUrl, String strUserName, String strPassword) {
        BufferedInputStream in = null;
        try {
            java.net.URL url = new java.net.URL(strUrl);
            java.net.HttpURLConnection connection = null;
            java.net.HttpURLConnection.setFollowRedirects(true);
            connection = (java.net.HttpURLConnection) url.openConnection();            
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
            connection.setRequestProperty("Content-Length", "0");
            connection.setRequestProperty("Connection", "close");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            
            connection.setAllowUserInteraction(true);
            connection.setDefaultUseCaches(false);
            
            //Base64 b64 = new Base64();
            String userPass;
            userPass = strUserName + ":" + strPassword;
            userPass=com.rockville.httpRequest.Base64Coder.encodeString(userPass);
            connection.setRequestProperty("Authorization", "Basic " + userPass);
            
            int intResponseCode = connection.getResponseCode();
            if (intResponseCode != 200) {
                log.debug("response code from " + strUrl + " is not 200 with strUserName: strPassword");
                return null;
            }

            //in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            in=new BufferedInputStream(connection.getInputStream() );
            
            return in;
            
        } catch (Exception e) {
            log.error("Exception (" + strUrl + ") ", e);
        }
        return null;
    }
    public static String HttpPostUrl(String strUrl) {
        String strResponse = "";
        //log.debug("strUrl: " + strUrl);
        java.net.URL url = null;
        java.net.HttpURLConnection connection = null;
        
        try {
            url = new java.net.URL(strUrl);
            java.net.HttpURLConnection.setFollowRedirects(true);
            connection = (java.net.HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            
            connection.setAllowUserInteraction(true);
            connection.setDefaultUseCaches(false);
            connection.setRequestProperty("contenttype", "text/html");

            
            connection.setRequestProperty("Content-length", "0");
            PrintWriter pw = new PrintWriter(connection.getOutputStream());            
            pw.flush();
            pw.close();
            
            int intResponseCode = connection.getResponseCode();
            //log.debug("" + intResponseCode + " : " + strUrl + " in HttpRequestUrl(String strUrl,String strParamName,String strParamValue) in MZReports.java");
            if (intResponseCode != 200) {
                //log.debug("response code from " + strUrl + " is not 200 so not updating database");
                strResponse = "-1";
                return strResponse;
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                strResponse += inputLine;
            //log.debug(strResponse);
            }
            in.close();
            
        } catch (Exception e) {
            log.error("Exception (" + strUrl + ") ", e);
            strResponse = "-1";
        }
        finally {
            try {
                connection.disconnect();
                connection = null;
            }
            catch(Exception ex) {
                connection = null;
            }
        }
        return strResponse;
    }

    public static String downloadImage(String strUrl, String imageSavePath) {
    	String imgPath = imageSavePath;
    	try {
    		if(strUrl == null || strUrl.length() < 1)
    			return "";
			if(!(strUrl.startsWith("http://") || strUrl.startsWith("https://"))) {
				strUrl = "http://"+strUrl;
			}
	    	URL url = new URL(strUrl);
	    	String imgName = "";
    		try {
    	    	imgName = url.getFile();
    			imgName = imgName.substring(imgName.lastIndexOf("/")+1);
    			if(imgName.indexOf("?") > -1)
    				imgName = imgName.substring(0, imgName.indexOf("?"));
        	} catch(Exception e) {
        		log.error("Error getting Image Name, URL:"+strUrl, e);
        		return "";
        	}    		
	        InputStream in = url.openStream();
	        imgPath = imageSavePath+(imageSavePath.endsWith(File.separator)?"":File.separator)+imgName;
	        OutputStream out = new BufferedOutputStream(new FileOutputStream(imgPath));
	        for (int b; (b = in.read()) != -1; ) {
	            out.write(b);
	        }
	        out.close();
	        in.close();
	        log.info("Image downloaded from ("+strUrl+") and saved at ("+imgPath+")");
    	} catch(Exception e) {
    		log.error("Error downloading Image, URL:"+strUrl, e);
    	}
    	return imgPath;
    }
}
